package io.flash.rpc.protocol;

import com.alibaba.fastjson.JSON;
import io.flash.rpc.demo.ServiceFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class RpcRequestPacketHandler extends SimpleChannelInboundHandler<RpcRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequestPacket rpcRequestPacket) throws Exception {
        // 1. 解析服务对象
        Object service = ServiceFactory.getService(rpcRequestPacket.getServiceClassName());

        // 2. 解析方法对象
        Method method = ServiceFactory.getMethod(rpcRequestPacket);

        // 3. 解析参数对象
        Object param = JSON.parseObject(rpcRequestPacket.getParam(), method.getParameterTypes()[0]);

        // 4. 调用方法
        Object returnValue = method.invoke(service, param);

        // 5. 写回响应
        channelHandlerContext.writeAndFlush(new RpcResponsePacket(rpcRequestPacket.getRequestId(), JSON.toJSONString(returnValue)));


        // pipeline:  inbound: =======>handler========>handler==========>handler==========>handler
       //             outbound: <=======handler<========handler<==========handler<==========handler

    }
}
